//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package code_dao

import (
	"context"
	"fmt"

	"atomgit.com/openlinksaas/api-server/dao/db_ns"
	"atomgit.com/openlinksaas/proto-gen-go.git/project_code_api"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type ThreadInfoDbItem struct {
	ThreadInfoId      string   `bson:"_id"`
	ThreadId          string   `bson:"threadId"`
	ProjectId         string   `bson:"projectId"`
	CreateTime        int64    `bson:"createTime"`
	UpdateTime        int64    `bson:"updateTime"`
	CommentCount      uint32   `bson:"commentCount"`
	CommentUserIdList []string `bson:"commentUserIdList"`
	LastCommentId     string   `bson:"lastCommentId"`
}

func (item *ThreadInfoDbItem) ToThreadInfo(lastComment *project_code_api.Comment) *project_code_api.ThreadInfo {
	commentUserList := []*project_code_api.CommentUser{}
	for _, commentUserId := range item.CommentUserIdList {
		commentUserList = append(commentUserList, &project_code_api.CommentUser{
			CommentUserId: commentUserId,
		})
	}
	return &project_code_api.ThreadInfo{
		ThreadId:        item.ThreadId,
		CreateTime:      item.CreateTime,
		UpdateTime:      item.UpdateTime,
		CommentCount:    item.CommentCount,
		CommentUserList: commentUserList,
		LastComment:     lastComment,
	}
}

type _ThreadDao struct {
	mc *mongo.Collection
}

func newThreadDao(db *mongo.Database) (*_ThreadDao, error) {
	mc := db.Collection(db_ns.DB_NS_PROJECT_CODE + "thread")
	_, err := mc.Indexes().CreateOne(context.Background(), mongo.IndexModel{
		Keys: bson.D{{"projectId", 1}, {"updateTime", -1}},
	})
	if err != nil {
		return nil, err
	}
	return &_ThreadDao{mc: mc}, nil
}

func (db *_ThreadDao) Insert(ctx context.Context, dbItem *ThreadInfoDbItem) error {
	dbItem.ThreadInfoId = db.genThreadInfoId(dbItem.ProjectId, dbItem.ThreadId)
	_, err := db.mc.InsertOne(ctx, dbItem)
	return err
}

func (db *_ThreadDao) genThreadInfoId(projectId, threadId string) string {
	return fmt.Sprintf("%s:%s", projectId, threadId)
}

func (db *_ThreadDao) Exist(ctx context.Context, projectId, threadId string) (bool, error) {
	threadInfoId := db.genThreadInfoId(projectId, threadId)
	count, err := db.mc.CountDocuments(ctx, bson.M{"_id": threadInfoId, "projectId": projectId})
	return count > 0, err
}

func (db *_ThreadDao) Remove(ctx context.Context, projectId, threadId string) error {
	threadInfoId := db.genThreadInfoId(projectId, threadId)
	_, err := db.mc.DeleteOne(ctx, bson.M{"_id": threadInfoId, "projectId": projectId})
	return err
}

func (db *_ThreadDao) Update(ctx context.Context, projectId, threadId string, updateTime int64, commentCount uint32, userIdList []string, lastCommentId string) error {
	threadInfoId := db.genThreadInfoId(projectId, threadId)
	_, err := db.mc.UpdateOne(ctx, bson.M{"_id": threadInfoId, "projectId": projectId}, bson.M{"$set": bson.M{
		"updateTime":        updateTime,
		"commentCount":      commentCount,
		"commentUserIdList": userIdList,
		"lastCommentId":     lastCommentId,
	}})
	return err
}

func (db *_ThreadDao) UpdateLastCommitId(ctx context.Context, projectId, threadId string, lastCommentId string) error {
	threadInfoId := db.genThreadInfoId(projectId, threadId)
	_, err := db.mc.UpdateOne(ctx, bson.M{"_id": threadInfoId, "projectId": projectId}, bson.M{"$set": bson.M{
		"lastCommentId": lastCommentId,
	}})
	return err
}

func (db *_ThreadDao) Count(ctx context.Context, projectId string) (uint32, error) {
	count, err := db.mc.CountDocuments(ctx, bson.M{"projectId": projectId})
	return uint32(count), err
}

func (db *_ThreadDao) List(ctx context.Context, projectId string, offset, limit int64) ([]*ThreadInfoDbItem, error) {
	if limit == 0 {
		return []*ThreadInfoDbItem{}, nil
	}
	cursor, err := db.mc.Find(ctx, bson.M{"projectId": projectId}, options.Find().SetSkip(offset).SetLimit(limit).SetSort(bson.M{"updateTime": -1}))
	if err != nil {
		return nil, err
	}
	retList := []*ThreadInfoDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}

func (db *_ThreadDao) ListAll(ctx context.Context) ([]*ThreadInfoDbItem, error) {
	cursor, err := db.mc.Find(ctx, bson.M{})
	if err != nil {
		return nil, err
	}
	retList := []*ThreadInfoDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}
